package com.lizx.staff.controller;

import com.lizx.pojo.TbProject;
import com.lizx.staff.service.ProjectService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("staff/project")
public class ProjectController {

    @Resource
    ProjectService projcetService;

    //private static final String UPLOAD_DIR = "mydir/";
    private static final String UPLOAD_DIR = "/usr/local/mydir/financial/images/";

    @RequestMapping("list")
    public List<TbProject> list(){
        return projcetService.list();
    }

    @RequestMapping("uploadFile")
    @ResponseBody
    public String uploadFile(@RequestBody MultipartFile imgFile){
        System.out.println(imgFile.getOriginalFilename());

        String originalFilename = imgFile.getOriginalFilename();
        String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String imgName = UUID.randomUUID().toString().replace("-","")+prefix;

        try {
            // 确保目录存在
            LocalDate currentDate = LocalDate.now();
            int year = currentDate.getYear();
            int month = currentDate.getMonthValue();
            Path uploadPath = Paths.get(UPLOAD_DIR+year+"/"+month+"/");
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 保存文件
            Path filePath = uploadPath.resolve(imgName);
            Files.copy(imgFile.getInputStream(), filePath);
            return year+"/"+month+"/"+imgName;

        } catch (IOException e) {
            e.printStackTrace();
            return "File upload failed: " + e.getMessage();
        }
    }

}
